package net.spider.tools.page;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 * 获取PageHelper实例
 * 设置页面内容setContent（）
 * 设置提取规则addpatternsParts（）
 * 按照提取规则提取页面内容
 * 
 * 需要顺序setDocument();
 * 		addPatternParts();
 * 		run();/getUrls();
 * @author Administrator
 *
 */
public class PageHelper {
	//正则匹配区域
	private List<PickUpItem> patternParts=new ArrayList<PickUpItem>();
	private Document document=null;
	private Set<String> urls=null;
	
	public void addPatternParts(PickUpItem item){
		patternParts.add(item);
	}
	public void addAllPatternParts(List<PickUpItem> items){
		patternParts.addAll(items);
	}
	
	private Map<String, List<PickUpItem>> pickUpContentByPattern(){
		Map<String, List<PickUpItem>> allTagetItemsMap=new HashMap<String, List<PickUpItem>>();
		for (PickUpItem item:patternParts) {
			if(item.getMatchType().equals(MatchType.Expression)){
				//用正则匹配
			}else if(item.getMatchType().equals(MatchType.Css)){
				List<PickUpItem> itemsTemp=new ArrayList<PickUpItem>();
				//Css匹配
				Elements elments = document.select(item.getPattern());
				for(Element element : elments){
					PickUpItem targetItem=item.clone();
					targetItem.setTargetContent(element);
					itemsTemp.add(targetItem);
					allTagetItemsMap.put(item.getName(), itemsTemp);
				}
			}else if(item.getMatchType().equals(MatchType.Xpath)){
				//Xpath匹配
			}
		}
		return allTagetItemsMap;
	}
	
	public Set<String> getUrls() {
		if(urls==null){
			urls=getAllUrlsOfDocument();
		}
		return urls;
	}

	
	private Set<String> getAllUrlsOfDocument() {
		Set<String> linksOfPage=new HashSet<String>();
		Pattern pattern = Pattern.compile("^Java.*");
		Matcher matcher = pattern.matcher(this.document.html());
		while(matcher.find()){
			linksOfPage.add(matcher.group(0));
		}
		return linksOfPage;
	}

	private Document getDocument(){
		return document;
	}
	
	public void setDocument(Document document) {
		this.document = document;
	}

	public Map<String,List<PickUpItem>> run() {
		return pickUpContentByPattern();
	}
}
